<template>
  <div>
    <!-- 面包屑区域stat -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>
    <!-- 面包屑区域end -->

    <!-- 卡片视图区域stat -->
       <el-card>
            <el-row>
                <el-col :span="4">
                    <el-button type="primary" @click="addRoles">添加角色</el-button>
                </el-col>
            </el-row>
         </el-card>
    <!-- 卡片视图区域end -->

    <!-- 主体内容区域stat -->
            <el-table  :data="rolesList"   style="width: 100%" border  stripe>
                <el-table-column type="expand" >
                    <template v-slot="{ row }">
                    <el-row v-for="(item ,i1) in row.children" :key="item.id" :class="['bdbottom',i1===0?'bdtop':'', 'vcconten']">
                        <!-- 渲染一级权限start -->
                                <el-col :span="5">
                                    <el-tag closable @close="removeUserById(row,item.id)">{{item.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                            <!-- 渲染一级权限end -->
                            <!-- 渲染二级和三级权限start -->
                            <el-col :span="19">
                                <el-row  :class="[i2===0?'':'bdtop' , 'vcconten']" v-for="(item2 ,i2) in item.children" :key="item2.id">
                                    <!-- 渲染二级start -->
                                    <el-col :span="6">
                                    <el-tag closable type="success" @close="removeUserById(row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 渲染二级end -->
                                    <!-- 渲染三级权限start -->
                                    <el-col :span="18">
                                    <el-tag closable type="warning" v-for="(item3) in item2.children" :key="item3.id" @close="removeUserById(row,item3.id)">{{item3.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 渲染三级权限end -->

                                </el-row>
                            </el-col>
                            <!-- 渲染二级和三级权限end -->

                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#" ></el-table-column>
                <el-table-column prop="roleName"  label="角色名称"  ></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"  ></el-table-column>
                <el-table-column  label="操作">
                    <template slot-scope="scope">
                        <!-- 修改 -->
                    <el-button type="primary" icon="el-icon-edit" @click="eaitRoles(scope.row.id)"></el-button>
                        <!-- 删除 -->
                    <el-button type="danger" icon="el-icon-delete" circle @click="removeRolesForm(scope.row.id)"></el-button>
                        <!-- 角色 -->
                    <el-tooltip effect="dark" content="分配角色" placement="top" enterable>
                        <el-button type="warning" icon="el-icon-s-tools" circle @click="showgSetRight(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
    <!-- 主体内容区域end -->
    <!--展示分配权限对话框start -->
            <el-dialog
            title="分配权限"
            :visible.sync="roleDialogVisible"
            width="50%" @close="removeRoles">
            <!-- 树形控件start -->
                <el-tree :data="roleList" :props="roleProps"  show-checkbox default-expand-all node-key="id" :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
            <!-- 树形控件end -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="roleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
            </el-dialog>
    <!--展示分配权限对话框end  -->

    <!-- 添加角色start -->
          <el-dialog title="添加角色" :visible.sync="addDialogVisible"  width="50%" @close="addClose">
            <!-- 添加主体区域start -->
              <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
              <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="addForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                  <el-input v-model="addForm.roleDesc"></el-input>
              </el-form-item>
              </el-form>
            <!-- 添加主体区域end -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addRolesForm">确 定</el-button>
                </span>
                </el-dialog>
    <!-- 添加角色end -->

    <!-- 修改角色信息start -->
       <el-dialog title="添加角色" :visible.sync="eaitDialogVisible"  width="50%" @close="eaitClose">
            <!-- 添加主体区域start -->
              <el-form :model="eaitForm" :rules="eaitFormRules" ref="eaitFormRef" label-width="100px" >
              <el-form-item label="角色名称" prop="roleName">
                  <el-input v-model="eaitForm.roleName"></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="roleDesc">
                  <el-input v-model="eaitForm.roleDesc"></el-input>
              </el-form-item>
              </el-form>
            <!-- 添加主体区域end -->
                <span slot="footer" class="dialog-footer">
                    <el-button @click="eaitDialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="eaitRolesForm">确 定</el-button>
                </span>
                </el-dialog>
    <!-- 修改角色信息end -->
    </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      roleDialogVisible: false,
      roleList: [],
      //   树形控件
      roleProps: {
        children: 'children',
        label: 'authName'
      },
      defaultKeys: [],
      roleid: '',
      addDialogVisible: false,
      addForm: {},
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      },
      eaitDialogVisible: false,
      eaitForm: {},
      // 修改角色校验规则
      eaitFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.message.error('获取角色列表失败')
      }
      this.rolesList = res.data
    },
    // 删除角色权限
    async removeUserById (role, right) {
      const removeUser = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeUser !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${right}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      role.children = res.data
    },
    // 展示分配权限对话框
    async showgSetRight (role) {
      this.roleid = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.message.error('获取权限数据失败')
      }
      this.roleList = res.data
      this.getLeafKeys(role, this.defaultKeys)
      this.roleDialogVisible = true
    },
    // 通过递归的形式,获取角色下的三级权限的ID保存到defaultKeys
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => this.getLeafKeys(item, arr))
    },
    // 重置
    removeRoles () {
      this.defaultKeys = []
    },
    // 为角色分配权限
    async allotRights () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleid}/rights`, { rids: idStr })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.roleDialogVisible = false
    },
    // 展示添加角色对话框
    addRoles () {
      this.addDialogVisible = true
    },
    // 监听对话框关闭重置事件
    addClose () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮提交添加角色
    addRolesForm () {
      this.$refs.addFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.getRolesList()
        console.log(res.data)
      })
    },
    // 展示修改对话框显示与隐藏
    async eaitRoles (id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.eaitForm = res.data
      this.eaitDialogVisible = true
    },
    // 点击确定按钮提交修改角色
    eaitRolesForm () {
      this.$refs.eaitFormRef.validate(async vali => {
        if (!vali) return
        const { data: res } = await this.$http.put('roles/' + this.eaitForm.roleId, {
          roleName: this.eaitForm.roleName,
          roleDesc: this.eaitForm.roleDesc
        })
        console.log(res.data)
        if (res.meta.status !== 200) {
          this.$message.error('修改角色失败')
        }
        this.eaitDialogVisible = false
        this.getRolesList()
        this.$message.success('修改角色成功')
      })
    },
    // 监听修改角色关闭重置事件
    eaitClose () {
      this.$refs.eaitFormRef.resetFields()
    },
    // 点击删除按钮删除角色
    async removeRolesForm (id) {
      const removeRolesForm = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeRolesForm !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getRolesList()
    }
  }
}
</script>

<style  lang="less" scoped>
.el-tag {
    margin: 5px;
}
.bdtop {
    border-top: 1px solid #eee;
}
.bdbottom {
    border-bottom: 1px solid #eee;
}
.vcconten {
    display: flex;
    align-items: center;
}
</style>
